<?php

namespace App\Http\Controllers\Admin\Goods;

use App\B2BProject\Admin\AdminControllerBuildTrait;
use App\B2BProject\Custom\Business\Brand;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class brandsController extends Controller
{
    use AdminControllerBuildTrait;

    protected $moduleName = '';

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        if ($request->ajax()) {
            $query = Brand::orderBy('created_at','desc');

            if ($brand_name = $request->query('brandFullName')) {
                $query = $query->where('name', 'like', "%$brand_name%");
            }

            $brands = $query->orderBy('created_at', 'desc')->paginate($request->query('pageSize', 7));

            $data = [];
            foreach ($brands as $brand) {
                $item   = [
                    'id'            => $brand->id,
                    'name'          => $brand->name,
                    'logo'          => $brand->logo,
                    'sort'          => $brand->sort,
                    'recommend'     => $brand->recommend,
                    'category_name' => '咖啡物料', // TODO 日后需要调整！
                    'edit_href'     => route('admin.goods.brand.edit', [$brand->id, 'page' => $request->input('page')]),
                    'delete_href'   => route('admin.goods.brand.destroy',
                        [$brand->id, 'page' => $request->input('page')]),
                ];
                $data[] = $item;
            }
            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $brands->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $brands->total(),
                ],
            ]);
        }

        return view('admin/goods/brands/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin/goods/brands/edit')->with('form', route('admin.goods.brand.index'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'name'      => 'required',
                'sort'      => 'numeric',
                /* 'display'   => 'boolean',*/
                'recommend' => 'boolean',
            ]
        );
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }
        $data = $request->only(['name', 'sort', 'recommend']);// 只取这些数据
        if ($request->hasFile('logo')) {
            $file         = $request->file('logo');
            $file_name    = Str::random(8) . '.' . $file->getClientOriginalExtension();
            $target       = $file->move(base_path('public/data/upload/brands'), $file_name);
            $target       = str_replace(base_path('public'), '', $target);
            $data['logo'] = $target;
        }
        $data['display'] = 1;
        $brands          = new Brand();
        $brands->create($data);
        return redirect()->route('admin.goods.brand.index');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $brand = Brand::findOrNew($id);

        return view('admin/goods/brands/edit')->with('brand', $brand)->with('form',
            route('admin.goods.brand.update', [$brand->id, 'page' => $request->input('page')]));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'name'      => 'required',
                'sort'      => 'numeric',
                /* 'display'     => 'required',*/
                'recommend' => 'required',
            ]
        );
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }
        $data = $request->only(['name', 'sort', 'recommend']);// 只取这些数据
        if ($request->hasFile('logo')) {
            $file      = $request->file('logo');
            $file_name = Str::random(8) . '.' . $file->getClientOriginalExtension();
            $target    = $file->move(base_path('public/data/upload/brands'), $file_name);
            $target    = str_replace(base_path('public'), '', $target);

            $data['logo'] = $target;
        }

        $brand = Brand::findOrFail($id);
        $brand->update($data);

        return $this->index($request);
    }

    /**
     *
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $brand = Brand::findOrFail($id);
        $brand->delete();

        return $this->index($request);
    }

    /**
     * 批量删除  循环遍历id进行删除   暂时没用
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function batchRemove(Request $request)
    {
        try {
            return \DB::transaction(function() use ($request) {
                $arr = $request->input('ids');
                foreach ($arr as $brand_id) {
                    $brand = Brand::findOrFail($brand_id);
                    $brand->delete();
                }
                return $this->index($request);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }
}
